package com.hl.springboothome1.controller;

import com.hl.springboothome1.util.R;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("file")
@CrossOrigin
public class FileController {
    String rootPath = "D:\\upload\\";

    @RequestMapping("download")
    public void download(String fileName, HttpServletResponse response) throws IOException {
        //获取文件的文件流对象
        FileInputStream fin = new FileInputStream(new File(rootPath+fileName));
        //设置响应的类型
        response.setHeader("content-Dispostion","filename="+fileName);//预览
        //获取响应流对象
        ServletOutputStream out = response.getOutputStream();
        //进行文件拷贝--读写操作
        IOUtils.copy(fin,out);
        out.close();
        fin.close();
    }

    @RequestMapping("download2")
    public void download2(String fileName, HttpServletResponse response) throws IOException {
        //获取文件的文件流对象
        FileInputStream fin = new FileInputStream(new File(rootPath+fileName));
        //设置响应的类型
        response.setHeader("content-Dispostion","attachmant;filename="+fileName);//预览
        //获取响应流对象
        ServletOutputStream out = response.getOutputStream();
        //进行文件拷贝--读写操作
        IOUtils.copy(fin,out);
        out.close();
        fin.close();
    }
    @PostMapping("upload")
    public R upload(MultipartFile file) throws IOException { //1.获取文件

        //判断文件是否为空
        if (file.isEmpty()){
            return R.fail();
        }
        //2.获取文件名
        String fileName = file.getOriginalFilename();
        //为了防止文件名重复，使用UUID
        fileName = UUID.randomUUID().toString().replace("-","")+"-"+fileName;
        //自动创建上传的文件夹名，当前日期文件夹
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMM");//规定日期格式
        String dirName = simpleDateFormat.format(new Date()); //按格式获取当前日期，并返回一个String类型的dirName
        File dirFile = new File(rootPath,dirName); //使用dirname拼接rootPath 得到完整的上传路径
        if (!dirFile.exists()){  //判断文件夹是否存在
            dirFile.mkdirs(); //如果不存在就创建文件夹
        }
        //组成完整的上传后的路径
        //3.上传
        file.transferTo(new File(dirFile,fileName)); //再用获取到的dirfile拼接文件名
        //4.返回结果
        //真实上传的路径
        String fileRealName = dirName+"/"+fileName;
        return R.ok(fileRealName);
    }
}
